import model from 'model'
import notify from '../../components/notification/function'
import bus from '../../util/bus'


const handleError = (err) =>{
  if(err.code===401){
    notify({
      content: '你得先登录啊！'
    })
    bus.$emit('auth')
  }
}

export default {
  fetchCourses ({ commit }) {
    commit('startLoading')
    return model.getAllCourses()
      .then(data => {
        commit('endLoading')
        commit('fillCourses', data)
      })
      .catch(err => {
        commit('endLoading')
        handleError(err)
      })
  },
  login({commit},{username,password}) {
    commit('startLoading')
    return new Promise((resolve,reject)=>{
      model.login(username,password)
      .then(data=>{
        commit('doLogin',data)
        notify({
          content: '登录成功'
        })
        resolve()
        commit('endLoading')
      }).catch(err=>{
        handleError(err)
        reject(err)
        commit('endLoading')
      })
    })
  }
}
